package ext.tianma.doc.util;

import java.rmi.RemoteException;

import org.apache.commons.lang.StringUtils;

import ext.com.core.CoreUtil;
import ext.com.iba.IBAUtil;
import ext.com.workflow.WorkflowUtil;
import ext.generic.erp.common.CommonPDMUtil;
import ext.tianma.part.forms.TMTypeUtil;
import ext.tianma.util.IbaAttributeUtil;
import ext.tianma.util.TianMaConstants;
import wt.doc.WTDocument;
import wt.fc.ObjectReference;
import wt.fc.QueryResult;
import wt.fc.WTObject;
import wt.fc.collections.WTArrayList;
import wt.identity.IdentityFactory;
import wt.type.ClientTypedUtility;
import wt.util.WTException;

public class DocWorkflowUtil {
	// 文档大类
	private static final String PROCESS_DOCUMENTS = ".ProcessDocuments";
	// 文档小类
	private static final String SMALL_DOC_TYPE = "SmallDocType";
	private static final String SMALL_DOC_TYPE_VALUES = "FPC受控图纸";

	/**
	 * 判断文档类型
	 * 
	 * @param object
	 * @return
	 * @throws WTException
	 * @throws RemoteException
	 */
	public static String checkDoc(Object object) throws WTException, RemoteException {
		String doc = "";
		if (object == null) {
			return "";
		}

		if (object instanceof ObjectReference) {
			ObjectReference ref = (ObjectReference) object;
			object = ref.getObject();
		}

		if (object instanceof WTDocument) {
			WTDocument wd = (WTDocument) object;
			String name = ClientTypedUtility.getTypeIdentifier(wd).getTypename();
			Object dw = IBAUtil.getIBAValue(wd, SMALL_DOC_TYPE);
			if (name == null || dw == null) {
				return doc;
			}
			if (name.contains(PROCESS_DOCUMENTS) || (SMALL_DOC_TYPE_VALUES).equals(dw)) {
				doc = "Y";
			}
		}
		return doc;
	}

	/**
	 * 获取文档的随迁对象
	 * 
	 * @param wtObject
	 * @return
	 */
	public static WTArrayList getDocArrayList(WTObject wtObject) {
		WTArrayList wtList = new WTArrayList();
		System.out.println("Debug   getDocArrayList...");
		if (wtObject != null) {

			if (wtObject instanceof WTDocument) {
				WTDocument doc = (WTDocument) wtObject;
				try {
					QueryResult qr = CoreUtil.getDependsOnDocuments(doc);

					if (qr != null) {

						while (qr.hasMoreElements()) {
							Object object = qr.nextElement();
							if (object != null && object instanceof ObjectReference) {
								ObjectReference orf = (ObjectReference) object;
								object = orf.getObject();
							}

							if (object != null && object instanceof WTDocument) {
								WTDocument wtDoc = (WTDocument) object;
								System.out.println("Debug   wtDoc:" + wtDoc.getNumber());
								wtList.add(wtDoc);
							}
						}
					}
				} catch (WTException e) {
					e.printStackTrace();
				}
			}
		}
		return wtList;
	}

	/**
	 * 设置状态
	 * 
	 * @param wtList
	 */
	public static void setAllPartState(WTArrayList wtList, String state) {

		if (wtList == null || state == null) {
			return;
		}

		for (int i = 0; i < wtList.size(); i++) {
			Object object = wtList.get(i);

			if (object != null && object instanceof WTDocument) {
				WTDocument wtDocument = (WTDocument) object;

				try {

					WorkflowUtil.setLifeCycleState(wtDocument, state);

				} catch (WTException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static void checkRelatedDocAndPart(Object object) throws WTException {
		if (object == null) {
			return;
		}

		if ((object instanceof WTDocument)) {
			WTDocument doc = (WTDocument) object;

			if (TMTypeUtil.isATypeObject(doc, ".ControlDocument")) {
				QueryResult partQ = CoreUtil.getAssociatedParts(doc);

				QueryResult docQ = CoreUtil.getDependsOnDocuments(doc);

				// modify by lilin 20181219 取消原档图纸校验 begin
				if (partQ == null) {// (partQ == null) || (docQ == null)
					throw new WTException("没有关联原档图纸和零部件");
				}

				if (partQ.size() == 0) {// (partQ.size() == 0) && (docQ.size() == 0)
					throw new WTException("没有关联原档图纸和零部件");
				}

				if (partQ.size() == 0) {
					throw new WTException("没有关联零部件");
				}

				// if (docQ.size() == 0)
				// throw new WTException("没有关联原档图纸");
				// modify by lilin 20181219  取消原档图纸校验 end
			}
		}
	}

	public static void checkDocTypeAndCheckOut(WTArrayList list) throws WTException {
		if ((list == null) || (list.size() <= 1)) {
			return;
		}

		for (int i = 0; i < list.size(); i++) {
			Object object = list.get(i);

			if (object != null) {
				if ((object instanceof ObjectReference)) {
					ObjectReference orf = (ObjectReference) object;
					object = orf.getObject();
				}

				if ((object instanceof WTDocument)) {
					WTDocument doc = (WTDocument) object;
					if (WorkflowUtil.isObjectCheckedOut(doc)) {
						throw new WTException("请将所有的随迁对象检入到系统中");
					}

					if (!TMTypeUtil.isATypeObject(doc, ".ProcessDocuments"))
						throw new WTException("随迁对象类型必须为工艺文件");
				}
			}
		}
	}

	public static void checkDocVersion(Object object) throws WTException {
		if ((object instanceof ObjectReference)) {
			ObjectReference ref = (ObjectReference) object;
			object = ref.getObject();
		}

		if ((object instanceof WTDocument)) {
			WTDocument doc = (WTDocument) object;
			if (getSoftTypeInternal(doc).equals("ControlDocument")) {
				WTArrayList list = getDocArrayList(doc);
				if (list.size() > 0)
					for (int i = 0; i < list.size(); i++) {
						WTDocument relatedDoc = (WTDocument) list.get(i);
						if (getSoftTypeInternal(relatedDoc).equals("InitialDrawingDoc")) {
							String majorVersion = CommonPDMUtil.getMajorVersion(relatedDoc);
							String minorVersion = CommonPDMUtil.getMinorVersion(relatedDoc);

							if (majorVersion.equals("0")) {
								System.out.println("majorVersion = 0");
							} else if (minorVersion.equals("0"))
								throw new WTException(
										"原档图纸" + IdentityFactory.getDisplayIdentifier(relatedDoc) + "没有编辑，请检出修改后再提交！");
						}
					}
			}
		}
	}

	public static String getSoftTypeInternal(WTObject obj) {
		String internalName = "";

		if (obj != null) {
			try {
				internalName = ClientTypedUtility.getTypeIdentifier(obj).getTypename();

				if (internalName != null) {
					int startIndex = internalName.lastIndexOf(".") + 1;

					internalName = internalName.substring(startIndex);
				}
			} catch (WTException e) {
				e.printStackTrace();
			}
		}

		return internalName;
	}

	/***
	 * 检查受控文档的研发地是否为武汉或者厦门
	 * 
	 * @param object
	 * @return boolean
	 * @throws WTException
	 */
	public static boolean checkDevelopedLand(Object object) {
		boolean flag = false;
		if (object == null) {
			return flag;
		}

		if ((object instanceof WTDocument)) {
			WTDocument doc = (WTDocument) object;

			if (TMTypeUtil.isATypeObject(doc, ".ControlDocument")) {
				String developedLand = IbaAttributeUtil.getAttributeValue(doc, "modulesDevelopedLand");
				if (StringUtils.isNotBlank(developedLand)) {
					String land = TianMaConstants.DevelopLand.getLand(developedLand);
					if (land.equals(developedLand)) {
						flag = true;
					}
				}
			}
		}
		return flag;
	}

	public static void main(String[] args) {

		if (args == null || args.length != 1) {
			System.out.println("Debug   参数列表有问题!");
			return;
		}
		try {
			WTObject wtObject = CoreUtil.getWTObjectByOid(args[0]);

			if (wtObject != null && wtObject instanceof WTDocument) {
				System.out.println("Debug   获取到的对象:" + ((WTDocument) wtObject).getNumber());
				WTArrayList list = getDocArrayList(wtObject);

				if (list != null) {
					System.out.println("Debug   获取完毕:" + list.size());
					for (int i = 0; i < list.size(); i++) {
						Object wtO = list.get(i);
						if (wtO != null && wtO instanceof WTDocument) {
							WTDocument wtDoc = (WTDocument) wtO;
							System.out.println("Debug   相关对象文档：" + wtDoc.getNumber());

						}
					}
				}
			}
		} catch (WTException e) {
			e.printStackTrace();
		}
	}

	/*
	 * public static void setProjectAttribute(WTDocument wtDoc) { if (wtDoc == null)
	 * { return; }
	 * 
	 * List list = getObjectSharedProject(wtDoc);
	 * 
	 * if ((list != null) && (list.size() > 0)) { Iterator iterator =
	 * list.iterator();
	 * 
	 * while (iterator.hasNext()) { Project2 pro = (Project2)iterator.next();
	 * 
	 * if (pro != null) try { IBAUtil.forceSetIBAValue(pro, "isProduction", "是");
	 * 
	 * String url =
	 * "http://pdmtest.tianma.com/Windchill/app/#ptc1/tcomp/infoPage?oid=VR%3Awt.doc.WTDocument%3A";
	 * 
	 * ReferenceFactory rf = new ReferenceFactory(); String ooid =
	 * rf.getReferenceString(wtDoc); int it = ooid.lastIndexOf(":"); String ur =
	 * ooid.substring(it + 1, ooid.length());
	 * 
	 * url = url + ur;
	 * 
	 * IBAURLUtil.setIBAValueOfUrl(pro, "documentURT", url, wtDoc.getNumber()); }
	 * catch (WTException e) { e.printStackTrace(); } } } }
	 * 
	 * public static List<Project2> getObjectSharedProject(Persistable perObj) {
	 * List list = new ArrayList();
	 * 
	 * Collection collection = null; try { collection =
	 * SandboxHelper.service.getInteropObjects(perObj); } catch (WTException e) {
	 * e.printStackTrace(); }
	 * 
	 * if (collection != null) { Iterator iterator = collection.iterator();
	 * 
	 * while (iterator.hasNext()) { Persistable persistable =
	 * (Persistable)iterator.next();
	 * 
	 * if ((persistable instanceof SharedContainerMap)) { SharedContainerMap
	 * containerMap = (SharedContainerMap)persistable;
	 * 
	 * WTContainerRef containerRef = containerMap.getTargetContainerRef();
	 * 
	 * if (containerRef != null) { WTContained wtContained =
	 * containerRef.getContainer();
	 * 
	 * if (wtContained != null) { list.add((Project2)wtContained); } } } } }
	 * 
	 * return list; }
	 */
}
